﻿Imports IICBusinessLogic

''' <summary>
''' Handles the User Interface for selecting students to a class
''' </summary>
''' <remarks>
''' </remarks>
Public Class UIClassMemberSelector

    Public Function selectMembers(ByVal PeriodClass As PeriodClass) As Boolean
        'Me.RefreshPanel2Grid()
        If PeriodClass.Period.IsOpen.GetValueOrDefault = False Then
            Call winUtils.MsgboxStop("Cannot add members to a class in a closed period.")
            Return False
        End If
        Dim retValue As Boolean = False

        Dim f As New Forms.List.frmStudentListSelect
        Try
            f.setClasssToAddStudents(PeriodClass)
            f.Size = New Size(Screen.PrimaryScreen.Bounds.Width - 100, _
                              Screen.PrimaryScreen.Bounds.Height - 100)

            If f.ShowDialog = DialogResult.OK Then
                Dim cmdb As New ClassMemberDBMapper

                Try
                    Dim sman As IStudentClassManager = New StudentClassManagerFactory().getStudentClassManager
                    cmdb.beginTrans()

                    For Each row As DataGridViewRow In f.grdData.SelectedRows

                        Dim studentId As Integer = CInt(row.Cells("StudentId").Value)
                        If PeriodClass.hasStudent(studentId) = False Then

                            retValue = True
                            'if even one student was selected and will be added to the period class, 
                            'set return value to true
                            Dim s As Student = StudentDataUtils.findByKey(studentId)
                            Dim c As ClassMember = sman.addStudentToClass(s, PeriodClass)

                            'ClassMemberDataUtils.saveClassMember(c)
                            '-- do not call dataustils method in a loop since each call 
                            '   instantiates a new instance of ClassMemberDBMapper

                            Call cmdb.save(c)

                        End If
                    Next
                    cmdb.commitTrans()

                Finally
                    cmdb.rollbackTrans()
                End Try

            End If

        Finally
            If f IsNot Nothing Then
                f.Dispose()
            End If
        End Try

        Return retValue

    End Function

End Class
